<template>
  <div>
    <Category :scene="scene"></Category>
    <el-card shadow="hover" style="margin-top: 10px">
      <div v-show="scene == 0">
        <el-button
          type="primary"
          :icon="Plus"
          @click="addAttr"
          v-hidden="'btn.Attr.add'"
          :disabled="!useCategoryStore.category3Id"
          >添加属性</el-button
        >
        <el-table style="margin-top: 10px" :data="attrList" border stripe>
          <el-table-column type="index" label="序号" width="80px" />
          <el-table-column
            prop="attrName"
            show-overflow-tooltip
            label="属性名称"
            width="140px"
          />
          <el-table-column label="属性值列表">
            <template #="{ row, index }">
              <el-tag
                class="ml-2"
                :type="attr.attrId % 2 == 0 ? 'success' : ''"
                v-for="(attr, index) in row.attrValueList"
                :key="attr.id"
                >{{ attr.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column prop="address" label="操作" width="140px">
            <template #="{ row, $index }">
              <el-button
                type="primary"
                :icon="Edit"
                size="small"
                @click="updateAttr(row)"
                v-hidden="'btn.Attr.update'"
              ></el-button>
              <el-popconfirm
                confirm-button-text="确定"
                cancel-button-text="取消"
                :icon="InfoFilled"
                icon-color="#626AEF"
                :title="`确认要删除${row.attrName}属性吗？`"
                @confirm="deleteAttr(row)"
                v-hidden="'btn.Attr.remove'"
              >
                <template #reference>
                  <el-button
                    type="danger"
                    :icon="Delete"
                    size="small"
                  ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="scene == 1">
        <el-form :inline="true">
          <el-form-item label="属性名">
            <el-input
              placeholder="请你输入属性的名字"
              clearable
              v-model="attrParams.attrName"
            />
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          :icon="Plus"
          :disabled="!attrParams.attrName"
          @click="addAttrValue"
          >添加属性值</el-button
        >
        <el-button @click="cancel">取消</el-button>
        <el-table
          border
          :data="attrParams.attrValueList"
          style="margin: 20px 0"
        >
          <el-table-column
            type="index"
            align="center"
            label="序号"
            width="80px"
          />
          <el-table-column label="属性值">
            <template #="{ row, $index }">
              <el-input
                v-if="row.flag"
                size="small"
                v-model="row.valueName"
                @blur="toLook(row, $index)"
                :ref="(el) => (inputArrRef[$index] = el)"
              ></el-input>
              <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #="{ row, $index }">
              <el-button
                type="danger"
                size="small"
                :icon="Delete"
                @click="deleteAttrValue($index)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          :disabled="!attrParams.attrValueList.length"
          @click="saveHandler"
          >保存</el-button
        >
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, reactive, nextTick, onUnmounted } from "vue";
import { Plus, Edit, Delete, InfoFilled } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { cloneDeep } from "lodash";

import categoryStore from "@/stores/category"; // store仓库
import {
  reqAttrList,
  reqAddOrUpdateAttr,
  reqDeleteAttr,
} from "@/api/product/attr"; // 请求函数
import type { IAttrList, IAttr, IAttrValue } from "@/api/product/attr/model"; // 数据类型

const useCategoryStore = categoryStore(); // Store仓库对象
const attrList = ref<IAttrList>([]); // 平台属性数据
const scene = ref<number>(0); // 控制场景切换
const inputArrRef = ref<any>([]); // input对象

// 添加或修改属性及属性值的参数
const attrParams = reactive<IAttr>({
  attrName: "",
  attrValueList: [],
  categoryId: undefined,
  categoryLevel: 3,
  id: undefined,
});

// 三级分类选中值变化时的回调, 获取平台属性数据
watch(
  () => useCategoryStore.category3Id,
  () => {
    if (useCategoryStore.category3Id) {
      getAttrList();
    }
  }
);

// 获取平台属性
const getAttrList = async () => {
  const result = await reqAttrList(
    useCategoryStore.category1Id,
    useCategoryStore.category2Id,
    useCategoryStore.category3Id
  );
  attrList.value = result;
};

// 添加属性按钮的回调
const addAttr = () => {
  scene.value = 1;

  Object.assign(attrParams, {
    attrName: "",
    attrValueList: [],
    categoryId: useCategoryStore.category3Id,
    categoryLevel: 3,
    id: undefined,
  });
};

// 取消添加按钮的回调
const cancel = () => {
  scene.value = 0;
};

// 添加属性值按钮的回调
const addAttrValue = () => {
  attrParams.attrValueList.push({
    valueName: "",
    flag: true,
  });

  nextTick(() => {
    inputArrRef.value[attrParams.attrValueList.length - 1].focus();
  });
};

// input框失去焦点切换查看模式
const toLook = (row: IAttrValue, index: number) => {
  if (!row.valueName.trim()) {
    ElMessage({
      showClose: true,
      message: "属性值名称必须有值",
      type: "warning",
    });
    attrParams.attrValueList.splice(index, 1);
    return;
  }

  let result = attrParams.attrValueList.find((item) => {
    if (row != item) {
      return row.valueName == item.valueName;
    }
  });

  if (result) {
    ElMessage({
      showClose: true,
      message: "属性值名称已存在",
      type: "warning",
    });
    attrParams.attrValueList.splice(index, 1);
    return;
  }

  row.flag = false;
};

// div点击切换编辑模式
const toEdit = (row: IAttrValue, index: number) => {
  row.flag = true;
  nextTick(() => {
    inputArrRef.value[index].focus();
  });
};

// 删除品牌属性值
const deleteAttrValue = (index: number) => {
  attrParams.attrValueList.splice(index, 1);
};

// 保存属性及属性值按钮的回调
const saveHandler = async () => {
  attrParams.attrValueList.forEach((item) => {
    if (item.hasOwnProperty("flag")) {
      delete item.flag;
    }
  });

  try {
    await reqAddOrUpdateAttr(attrParams);
    ElMessage({
      type: "success",
      showClose: true,
      message: attrParams.id ? "修改成功" : "添加成功",
    });
    scene.value = 0;

    getAttrList();
  } catch (error) {
    ElMessage({
      type: "warning",
      showClose: true,
      message: attrParams.id ? "修改失败" : "添加失败",
    });
  }
};

// 修改平台属性按钮的回调
const updateAttr = (row: IAttr) => {
  scene.value = 1;
  Object.assign(attrParams, cloneDeep(row));
};

// 删除平台属性按钮的回调
const deleteAttr = async (row: IAttr) => {
  try {
    await reqDeleteAttr(row.id);
    ElMessage({
      type: "success",
      message: "删除成功",
      duration: 500,
      showClose: true,
    });
    getAttrList();
  } catch (error) {
    ElMessage({
      type: "warning",
      message: "删除失败",
      duration: 500,
      showClose: true,
    });
  }
};

onUnmounted(() => {
  useCategoryStore.deleteCategory();
});
</script>

<style scoped></style>
